<template>
	<el-dialog :close-on-click-modal="false" title="精准选点(激活设备列表)" center :visible.sync="visible" :width="useRequestData?'70%':'40%'"
		@closed="dialogClose()">
		<el-table ref="exactTable" :data="exactList" stripe size="mini" tooltip-effect="dark" style="width: 100%;"
			max-height="400" border highlight-current-row :select-on-indeterminate="false"
			@selection-change="handleExactSelectionChange" @select-all="handleExactSelectAll"
			@select="handleExactSelect" row-key="id" v-if="useRequestData">
			<el-table-column type="selection" width="50" />
			<el-table-column label="点位" width="120" prop="media_type" />
			<el-table-column label="编号" width="120" prop="code" sortable />
			<el-table-column label="详情" min-width="200">
				<template slot-scope="scope">
					<span v-if="scope.row.media_type_pid==119">{{scope.row.building_number}} 号楼
						{{scope.row.unit_number}} 单元 {{scope.row.floor}} 层</span>
					<span v-else-if="scope.row.media_type_pid==120">
						{{scope.row.door_number}} 号门
						<span v-if="scope.row.media_type_id==135">{{scope.row.rail_number}} 号护栏</span>
					</span>
				</template>
			</el-table-column>
			<el-table-column label="特点" width="120" prop="media_feature" sortable />
		</el-table>
		<el-tree ref="exactTree" v-else :data="treeData" :props="treeProps" node-key="id" show-checkbox @check="checkTreeNode"
		@check-change="checkChange">
		</el-tree>
		<div class="margin-tb-xs text-sm">共计<span class="text-green">{{exactTotal || 0}}</span>个空闲，最多可选<span
				class="text-red">{{exactCanChoose>exactTotal?exactTotal:exactCanChoose}}</span>个</div>
		<span slot="footer" class="dialog-footer">
			<el-button type="primary" @click.native="confirmChoosed">确 定</el-button>
			<el-button @click.native="dialogClose()">取 消</el-button>
		</span>
	</el-dialog>
</template>

<script>
	import {
		building_area_active_can_devices //可用的激活点位
	} from '@/api/business/building/building';
	import common from '@/utils/common.js';
	import {
		isNumber,
		isArray,
		isObject,
		isTrue,
		isFunction,
		generateUUID,
		accMul,
		accAdd,
		accDiv,
		accSub,
		formatDate,
		getTimeSlot
	} from '@/utils/util.js'
	import {
		cloneDeep
	} from 'lodash'
	export default {
		name: 'ExactTable',
		// beforeRouteLeave(to, from, next) {
		// 	this.$destroy();
		// 	next();
		// },
		props: {
			exactVisible: {
				type: Boolean,
				default: false
			},
			buildingId: {
				type: String,
				required: true
			},
			pointTypeId: {
				type: String,
				required: true
			},
			dateRange: {
				type: Array,
				required: true
			},
			toExact: {
				type: Array,
				required: true
			},
			can: {
				type: Number,
				required: true
			},
			useRequestData: {
				type: Boolean,
				default: true
			},
			treeData: {
				type: Array,
				default: () => []
			},
			total: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				visible: this.exactVisible || false,
				exactKey: '',
				exactList: [],
				exactTotal: 0,
				exactCanChoose: 0,
				exactSelects: [],

				treeProps: {
					label: 'name',
					children: 'list'
				},
				
				choosed:[]
			}
		},
		mounted() {
			this.getExact();
		},
		methods: {
			dialogClose() {
				const that = this;
				that.resetExactList();
				that.visible = false;
				that.$emit('update:exactVisible', false);
			},
			// 精准选点
			getExact() {
				const that = this
				if (that.useRequestData) {
					if (that.buildingId && that.pointTypeId && that.dateRange[0] && that.dateRange[1]) {
						building_area_active_can_devices({
							id: that.buildingId,
							point_type_id: that.pointTypeId,
							start_at: that.dateRange[0],
							end_at: that.dateRange[1]
						}).then(({
							data
						}) => {
							that.exactList = cloneDeep(data || []);
							that.exactTotal = data.length || 0;
							that.exactCanChoose = that.can || 0;
							that.visible = true;
							that.$emit('update:exactVisible', true);
							that.$nextTick(() => {
								that.toggleSelection()
							})
						})
					}
				} else {
					that.visible = true;
					that.exactTotal = that.total || 0;
					that.exactCanChoose = that.can || 0;
					that.$emit('update:exactVisible', true);
					that.$nextTick(() => {
						that.toggleChecked()
					})
				}
			},
			// 处理勾选， 判断总数是否大于限制数
			handleExactSelectedOverCan(selection, row) {
				const that = this
				if (selection && isArray(selection)) {
					const sLen = parseInt(selection.length)
					if (selection.length > that.exactCanChoose) {
						if (row) {
							that.$refs.exactTable.toggleRowSelection(row, false);
							common.messageError('不允许勾选超出' + that.exactCanChoose + '个设备！')
						} else {
							for (let i = parseInt(that.exactCanChoose); i < sLen; i++) {
								let row = that.exactList[i];
								that.$refs.exactTable.toggleRowSelection(row, false);
							}
							common.messageSuccess('已勾选' + that.exactCanChoose + '个设备')
						}
					}
				}
			},
			// 全部勾选
			handleExactSelectAll(selection) {
				const that = this
				that.handleExactSelectedOverCan(selection)
			},
			// 勾选一行
			handleExactSelect(selection, row) {
				const that = this
				that.handleExactSelectedOverCan(selection, row)
			},
			// 表格多选
			handleExactSelectionChange(val) {
				const that = this
				that.choosed = val || [];
			},
			// 选择树节点
			checkTreeNode(a, b){
				const that = this;
				let choosedSet = new Set();
				let dMap = new Map();
				(b.halfCheckedNodes || []).concat(b.checkedNodes || []).forEach(d => {
					if(d.ruleId == 6){
						choosedSet.add(d.list[0].id);
						choosedSet.add(d.list[1].id);
						dMap.set(d.list[0].id, d.list[0]);
						dMap.set(d.list[1].id, d.list[1]);
					}else if(d.isLeaf){
						choosedSet.add(d.id);
						dMap.set(d.id, d);
					}
				});
				that.choosed = ([...choosedSet] || []).map(id => dMap.get(id));
				that.$refs.exactTree.setCheckedNodes(that.choosed || []);
			},
			// 选择某一个树节点
			checkChange(a, b, c){
				const that = this;
				if(a.type == 1 && a.isLeaf && b){
					const pNode = that.$refs.exactTree.getNode(a.pid).data;
					//console.log(pNode);
					const max = pNode.max;
					const checkedLeafs = that.$refs.exactTree.getCheckedKeys(true);
					if(((pNode.list || []).filter(d => checkedLeafs.indexOf(d.id) > -1) || []).length > max){
						that.$refs.exactTree.setChecked(a.id, false);
						common.messageError('超出规则上限:'+max+'个');
					}
				}
				if(a.type == 2 && a.isLeaf && b){
					const pNode = that.$refs.exactTree.getNode(a.pid).data;
					const rNode = that.$refs.exactTree.getNode(a.rid).data;
					const checkedLeafs = that.$refs.exactTree.getCheckedKeys(true);
					const pMax = pNode.max;
					const rMax = rNode.max;
					if(((pNode.list || []).filter(d => checkedLeafs.indexOf(d.id) > -1) || []).length > pMax){
						that.$refs.exactTree.setChecked(a.id, false);
						common.messageError('超出规则上限:一层'+pMax+'个');
					}
					let rdList = [];
					(rNode.list || []).forEach(p => {
						rdList = rdList.concat(p.list || []);
					});
					if((rdList.filter(d => checkedLeafs.indexOf(d.id) > -1) || []).length > rMax){
						that.$refs.exactTree.setChecked(a.id, false);
						common.messageError('超出规则上限:一单元'+rMax+'个');
					}
				}
			},
			confirmChoosed(){
				const that = this;
				that.$emit('choosed', that.choosed || []);
				that.dialogClose();
			},
			toggleChecked(){
				const that = this;
				that.$refs.exactTree.setCheckedNodes(that.toExact || []);
				that.choosed = that.$refs.exactTree.getCheckedNodes(true) || [];
			},
			toggleSelection() {
				const that = this
				if (that.exactList && isArray(that.exactList) &&
					that.toExact && isArray(that.toExact)) {
					let idSet = new Set();
					let dMap = new Map();
					let list = [];
					that.toExact.forEach(item => {
						idSet.add('' + item.id);
						dMap.set('' + item.id, item);
					})
					that.exactList.forEach(row => {
						if (idSet.has('' + row.id)) {
							that.$refs.exactTable.toggleRowSelection(row);
							list.push(dMap.get('' + row.id));
						}
					});
					that.choosed = list || [];
				} else {
					that.$refs.exactTable.clearSelection();
					that.choosed = [];
				}
			},
			// 重置精准选点相关数据
			resetExactList() {
				const that = this
				that.exactKey = ''
				that.exactList = []
				that.exactTotal = 0
				that.exactCanChoose = 0
				that.exactSelects = []
			},
		}
	}
</script>

<style>
</style>
